export default {
  namespaced: true,
  state: {
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('CART') || '[]')
  },
  getters: {
    // 商品数量
    total (state) {
      // let c = 0
      // state.cart.forEach(x=> c+= x.goods_count)
      // return c
      return state.cart.reduce((total,item)=> total+=item.goods_count,0)
    },
    // 选中的商品数量
    checkoutCount (state) {
      return state.cart.filter(x => x.goods_state === 2).reduce((total,item) => total += item.goods_count, 0)
    },
    // 统计选中商品总价
    checkedGoodsTotal (state) {
      return state.cart.filter(x => x.goods_state === 2).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
    }
  },
  mutations: {
    // 加入购物车事件
    addToCart (state, goods) {
      // 判断点击的商品在 cart 中是否有
      const findResults  = state.cart.find(x=> x.goods_id == goods.goods_id)
      // 如果有 findResults 为 underfind 否侧为对应的商品信息
      if (!findResults) {
        state.cart.push(goods)
      } else {
         findResults.goods_count++
      }
      this.commit('m_cart/saveCart')
    },
    // 存储到本地存储
    saveCart (state) {
       uni.setStorageSync('CART',JSON.stringify(state.cart))
    },
    // 删除商品 
    removeGodds(state, goods) {
      state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
      // 持久化保存
      this.commit('m_cart/saveCart')
    },
    // 修改商品是否选中
    updateGoodsState (state, goods) {
      // 判断是否有此商品
       const findResults = state.cart.find(x => x.goods_id === goods.goods_id)
       // 如果有修改结果
       if (findResults) {
         findResults.goods_state === 1 ?  findResults.goods_state = 2 : findResults.goods_state = 1
         // 持久化保存
         this.commit('m_cart/saveCart')
       }
    },
    // 修改商品数量
    updateGoodsCount (state, goods) {
      // 判断是否有此商品
      const findResults = state.cart.find(x => x.goods_id === goods.goods_id)
      // 如果有修改结果
      if (findResults) {
        findResults.goods_count = goods.goods_count
        // 持久化保存
        this.commit('m_cart/saveCart')
      }
    },
    // 全选反选功能
    updateAllGoodsState (state, newState) {
      // 数据不对
      state.cart.forEach(item => {
       if(newState) {
         item.goods_state = 2
       } else {
         item.goods_state = 1
       }
      })
      // state.cart.forEach(x => x.goods_state = newState)
      // 持久化保存
      this.commit('m_cart/saveCart')
    }
  },
  actions: {}
}
